class Solution
{
public:
    int maxSumDivThree(vector<int> &nums)
    {
        int n = nums.size();
        vector<vector<int>> dp(3, vector<int>(n, 0));
        dp[0][0] = 0;
        dp[1][0] = dp[2][0] = INT_MIN;
        dp[nums[0] % 3][0] = nums[0];
        for (int i = 1; i < n; ++i)
        {
            for (int lastMod = 0; lastMod < 3; ++lastMod)
            {
                int thisMod = (nums[i] + lastMod) % 3;
                dp[thisMod][i] = max(dp[thisMod][i - 1], dp[lastMod][i - 1] + nums[i]);
            }
        }
        return max(dp[0][n - 1], 0);
    }
};